<template>
    <div class="order-detail">
        <div class="detail">
            <div class="header">
                <div class="state">{{status.msg}}<span v-if="status.num">（{{status.num}}）</span></div>
                <div class="leftTime" v-if="status.times">
                    {{countDownList.day}}:{{countDownList.hour}}:{{countDownList.minute}}:{{countDownList.second}}:{{countDownList.millisecond}}
                </div>
            </div>
            <div v-if="['2','3'].includes(list.status)">
                <div class="logistics" v-for="(log, key) in logistics" :key="key"  @click="onSteps(log)">
                    <svg class="icon logistics-icon" aria-hidden="true">
                        <use xlink:href="#icon-Logistics"></use>
                    </svg>
                    <div class="content">
                        <div>{{log.company}}</div>
                        <div class="time">{{log.created}}</div>
                    </div>
                    <svg class="icon right" aria-hidden="true">
                        <use xlink:href="#icon-chevronright"></use>
                    </svg>
                </div>
            </div>

            <div class="address">
                <svg class="icon position" aria-hidden="true">
                    <use xlink:href="#icon-Positioning"></use>
                </svg>
                <div class="address-body" v-if="address">
                    <div class="address-top">
                        <div>{{address.rec_name}}</div>
                        <div>{{address.rec_phone}}</div>
                    </div>
                    <div class="address-detail">{{address.rec_province + address.rec_city + address.rec_area +
                        address.rec_detail}}
                    </div>
                </div>
            </div>
            <div class="order">
                <div class="number">
                    <div>订单号:{{list.id}}</div>
                    <div class="time">{{list.created}}</div>
                </div>
                <div class="line"></div>

                <div class="line"></div>
                <group-order-btn :good="btnList" :active="Number(active)" msg="拼团商品" type="detail" @finishCancel="finishCancel" v-if="list"/>
                <div class="line"></div>
                <div v-for="(good,index) in list.products" :key="good.id">
                    <order-single-goods :good="good" :index="index" :type="1" :remarkShow="true"/>
                    <!--<div class="refund-b"-->
                    <!--v-if="['1','2','3'].includes(list.status) && list.sub_status != '10'">-->
                    <!--<div class="refund" v-if="['2','3'].includes(list.status)" style="margin-right: 15px" @click="onSteps(good.id)">查看物流</div>-->
                    <!--<div class="refund" @click="goRefund(good.gid,good.buyid)">去退款</div>-->
                    <!--</div>-->
                    <div class="line"></div>
                </div>
                <div class="freight">
                    <div>运费:</div>
                    <div>{{list.freight | moneyFmt(2, '￥')}}</div>
                </div>
                <div class="line"></div>
                <div class="total">
                    <div>商品总金额</div>
                    <div class="price">{{list.money | moneyFmt(2, '￥')}}</div>
                </div>
            </div>
            <div class="question" @click="toServer">
                对此订单有疑问/投诉
                <svg class="icon right" aria-hidden="true">
                    <use xlink:href="#icon-chevronright"></use>
                </svg>
            </div>
        </div>

        <div class="detail-bottom" v-if="isCancel || isInit || isPartCancel">
            <div class="cancel-btn" @click="cancelGroup" v-if="isCancel">取消拼团</div>
            <div class="cancel-btn" @click="cancelPartGroup" v-if="isPartCancel">取消订单</div>
            <div class="initiate-btn" @click="initiateGroup" v-if="isInit">发起拼团</div>
        </div>
        <confirm ref="confirm_cancel" text="拼团取消后该团将会解散，确定取消吗?" confirmBtnText="确定取消" cancelBtnText="我再想想" @confirm="goRefund"/>
        <confirm ref="cancel" text="取消订单后将会退出该拼团，确定取消吗?" confirmBtnText="确定取消" cancelBtnText="我再想想" @confirm="goRefund"/>
    </div>
</template>

<script>
    import API from '../../../request/api';
    import {commonMixin} from '@/common/mixin';
    import OrderBtn from "../../../components/User/orderbtn";
    import OrderSingleGoods from "@/components/common/order-single-goods";
    import Confirm from "../../../components/common/confirm";
    import GroupOrderBtn from "../../../components/User/groupOrderBtn";

    export default {
        components: {
            GroupOrderBtn,
            Confirm,
            OrderSingleGoods, OrderBtn},
        mixins: [commonMixin],
        data() {
            return {
                list: {},
                status: {}, // 拼团订单状态
                address: {},
                active: this.$route.query.active,
                type: 1,
                btnList:{}, // 用于传入按钮组件
                countDownList: {
                    day: '00',
                    hour: '00',
                    minute: '00',
                    second: '00',
                    millisecond: 0
                },
                logistics: [], // 物流信息
            };
        },
        watch: {
            // 监听具体数据变化，并做相应的处理
        },
        computed: {
            isInit(){ // 能否发起拼团
                let init = false;
                if(JSON.parse(this.active)){
                    //0：失败   1：进行中  2：确认收货 3：已结束   4：（未付款/已失效）
                    if(['1','2'].includes(this.status.status) && this.status.times > 0){
                        init = true
                    }
                }
                return init
            },
            isCancel(){ // 能否取消拼团
                let init = false;
                if(JSON.parse(this.active)) {
                    //0：失败   1：进行中  2：确认收货 3：已结束   4：（未付款/已失效）
                    // if (['1', '2'].includes(this.status.status)) {
                    if(['1','2','3'].includes(this.list.status) && this.list.sub_status != '10'){
                        init = true
                    }
                }
                return init
            },
            isPartCancel(){ // 能否取消订单
                let init = false;
                if(!JSON.parse(this.active)){
                    // sub_status=10 => 已返利
                    if(['1','2','3'].includes(this.list.status) && this.list.sub_status != '10'){
                        init = true
                    }
                    return init
                }
            },
            refundType() {
                // 0仅退款，2退货退款
                let status = this.list.status;
                if (status == '3' || status == '2') {
                    return '2';
                } else {
                    return '0';
                }
            }
        },
        methods: {
            getOrderDetail() {
                this.request.get(API.groupOrderInfo, {
                    pid: this.$route.query.pid
                }).then(res => {
                    this.list = res.info;
                    this.logistics = res.info.logistics;
                    this.address = res.info.address;
                    this.status = res.status;
                    let data = {...res.info};
                    this.btnList = {...data}
                    this.btnList.order_status = data.status;
                    // res.status:0=待付款,1=待发货,2=待收货,3=已收货,4=售后,5=待验证，6=已验证 (默认为10全部)
                    // 当后台给时间差
                    if ( res.status.times> 0) {
                        this.countDown(res.status.times);
                    }
                    // 当后台给截止时间-当前时间
                    // if ((res.status.times - res.status.now_time)> 0) {
                    //     this.countDown(res.status.times*1000, res.status.now_time*1000);
                    // }
                    setTimeout(()=>{
                        this.hideGlobaLoading(); //关闭loading
                    },1000);
                }, () => {
                    this.hideGlobaLoading();
                });
            },
            cancelGroup(){
                this.$refs.confirm_cancel.show()
            },
            cancelPartGroup(){
                this.$refs.cancel.show()
            },
            confirmCancelGroup(){
                // this.goRefund()
                // this.request.post(API.orderCancel, {
                //     oid: this.list.id
                // }).then(res => {
                //     this.$toast({
                //         message: '取消成功',
                //         duration: 1000
                //     });
                //     this.$router.replace({
                //         name: 'group-order-list',
                //     });
                // }, () => {
                // });
            },
            initiateGroup(){
                this.$router.push({
                    name: 'group-initiate',
                    query: this.$route.query
                });
            },
            goRefund() {
                // zcj去退款,判断是否已经发起过售后，避免第二次发起
                let sub_status = this.list.sub_status;
                let status = this.list.status;
                console.log('list...', this.list)
                if (sub_status == 6) {
                    this.$toast('该订单已进入售后，无法再次取消');
                    return;
                }
                let data = {
                    status: status,
                    oid: this.list.id,
                    gid: this.list.products[0].gid,
                    buyid: this.list.products[0].buyid,
                    refundType: this.refundType // 0仅退款，1退货退款
                };
                console.log('data...', data)
                if (status == '1' || status == '0') {
                    console.log('status...1=0', status)
                    if (sub_status == '2') {
                        console.log('sub_status..2.', sub_status)
                        //备货中，选择退款方式
                        this.$router.replace({
                            name: 'refund-select',
                            query: data
                        });
                    } else {
                        //待发货，跳转至仅退款
                        this.$router.replace({
                            name: 'online-refund',
                            query: data
                        });
                    }
                } else if (status == '2' || status == '3') {
                    console.log('status...2-3', status)
                    //待收货，选择退款方式
                    this.$router.replace({
                        name: 'refund-select',
                        query: data
                    });
                    //待收货，跳转至退货退款
                    // this.$router.push({
                    //     name: 'online-refund',
                    //     query: data
                    // });
                }
            },
            toServer() {
                window.location.href = `https://webchat.7moor.com/wapchat.html?accessId=95145560-4f70-11e9-bdb0-9354e1ad17a8&system=${this.userInfo.system_id}&uid=${this.userInfo.uid}`;

            },
            timeFormat(param) {
                return param < 10 ? '0' + param : param;
            },
            countDown(timeDiff) {
                let interval = setInterval(() => {
                    // 获取当前时间，同时得到活动结束时间数组
                    // let newTime = Number(new Date().getTime());
                    // newTime += 1
                    // console.log(endTime, 'endTime-fd',newTime, endTime - newTime > 0);
                    let obj = {};
                    let ms = 10;
                    timeDiff--;
                    // 如果活动未结束，对时间进行处理
                    if (timeDiff > 0) {
                        // if ( endTime > 0) {
                        // let time = parseInt(endTime - newTime-1);
                        let time = parseInt(timeDiff);
                        // 获取天、时、分、秒
                        let day = parseInt(time / (60 * 60 * 24));
                        let hou = parseInt(time % (60 * 60 * 24) / 3600);
                        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
                        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
                        obj = {
                            day: this.timeFormat(day),
                            hou: this.timeFormat(hou),
                            min: this.timeFormat(min),
                            sec: this.timeFormat(sec),
                        };

                    } else { // 活动已结束，全部设置为'00'
                        // this.list.status = '7';
                        this.getOrderDetail();
                        clearInterval(interval);
                    }
                    this.countDownList.day = obj.day;
                    this.countDownList.hour = obj.hou;
                    this.countDownList.minute = obj.min;
                    this.countDownList.second = obj.sec;

                    let interval1 = setInterval(()=>{
                        if(ms){
                            this.countDownList.millisecond =  ms - 1;
                            ms--;
                        }
                    }, 100);
                }, 1000);
                // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
                this.$once('hook:beforeDestroy', () => {
                    clearInterval(interval);
                });
            },
            finishCancel() {
                this.$toast({
                    message: '取消成功',
                    duration: 1000
                });
                this.$router.go(-1);
            },
            onSteps(log) {
                console.log('loglog',log);
                // 跳转物流详情
                this.$router.push({
                    name: 'logistics',
                    query: {
                        ID: this.$route.query.oid,
                        number: log.number
                    }
                });
            }
        },
        beforeCreate() {
            // 可以在这加个loading事件，在加载实例时触发
            // 这个阶段实例的data、methods是读不到的
        },
        created() {
            this.showGlobaLoading();
            this.getOrderDetail();
            // 初始化数据，如在这结束loading事件，异步ajax请求也适宜在这里调用
            // 实例创建后：这个阶段已经完成了数据观测(data observer)，属性和方法的运算， watch/event 事件回调。
            // mount挂载阶段还没开始，"el" 属性目前不可见，数据并没有在DOM元素上进行渲染
        },
        beforeMount() {
            // 相关的 render 函数首次被调用。
        },
        mounted() {
            // 挂载元素，获取到DOM节点
            // el选项的DOM节点 被新创建的 vm的el 替换，并挂载到实例上去之后调用此生命周期函数。此时实例的数据在DOM节点上进行渲染
        },
        beforeUpdate() {
            // 数据更新时调用，但不进行DOM重新渲染，在数据更新时DOM没渲染前可以在这个生命函数里进行状态处理
        },
        updated() {
            //  如果对数据统一处理，在这里写上相应函数
            // 这个状态下数据更新并且DOM重新渲染，当这个生命周期函数被调用时，组件 DOM 已经更新，所以你现在可以执行依赖于 DOM 的操作。当实例每次进行数据更新时updated都会执行
        },
        beforeDestroy() {
            // 可以做一个确认停止事件的确认框
        },
        destroyed() {
            // Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，所有的事件监听器会被移除，所有的子实例也会被销毁
        }
    };

</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import '~assets/main.styl'
    .order-detail {
        overflow-x hidden
        height 100%
    }
    .detail{
        // border 1px solid salmon
        margin-bottom vw(75)
    }
    .header {
        background main-color 100% 100% no-repeat
        color grayF
        height vw(80)
        display flex
        flex-direction row
        justify-content flex-start
        align-items center
        padding cellPadding
        box-sizing border-box
        line-height 1.5
        .state {
            font-size word16
        }
        .leftTime {
            margin-left bigMargin
            font-size word16
        }
    }

    .logistics {
        display flex
        justify-content space-between
        padding cellPadding
        background-color grayF
        margin-bottom 1px
        align-items center
        .logistics-icon {
            color gray6
            width vw(20)
            height vw(20)
        }
        .content {
            flex: 1;
            font-size word12
            color gray3
            margin 0 smallMargin
            line-height 1.2
            .time {
                color gray9
                margin-top titleMargin
            }
        }
    }

    .address {
        display flex
        background-color grayF
        margin-bottom smallMargin
        padding cellPadding
        font-size word12
        flex 1
        .position {
            width vw(20)
            height vw(20)
        }
        .address-body {
            flex 1;
            margin-left smallMargin
        }
        .address-top {
            display flex
            justify-content space-between
            color gray3
            margin-bottom titleMargin

        }
        .address-detail {
            color gray9
        }
    }

    .order {
        background-color grayF
        .number {
            display flex
            justify-content space-between
            height vw(40)
            line-height vw(40)
            font-size word12
            color gray3
            padding 0 cellPadding
            .time {
                color gray9
            }
        }
        .title {
            display flex
        }
        .total {
            display flex
        }
        .refund-b {
            display flex
            justify-content flex-end
            margin-right cellPadding
            .refund {
                width vw(90)
                height vw(30)
                line-height vw(30)
                text-align center
                border 1px solid gray9
                color gray3
                font-size word12
                border-radius vw(20)

            }
        }

    }

    .freight, .total {
        display flex
        justify-content space-between
        font-size word14
        color gray3
        height vw(40)
        line-height vw(40)
        padding 0 cellPadding
        .price {
            font-size word16
            color main-color
        }
    }

    .question {
        text-align right
        margin-top smallMargin
        margin-bottom middleMargin
        background-color grayF
        height vw(45)
        line-height vw(45)
        padding 0 cellPadding
        font-size word14
    }
    .right {
        arrow()
    }
    .detail-bottom{
        margin-top middleMargin
        width 100%
        height vw(55)
        position fixed
        bottom 0
        background-color grayF
        display flex
        flex-direction row
        justify-content center
        align-items center
        .cancel-btn{
            secondary-hollow()
        }
        .initiate-btn{
            secondary-solid()
            margin-left middleMargin
        }
    }
</style>
